<?php
 require '../tools.func.php';
 require '../db.func.php';
 $id =intval($_GET['cart_id']) ;
 $quantity= intval($_GET['quantity']);
 $prefix=getprefix();
 $sql="SELECT name,price,id,code FROM {$prefix}product WHERE id='{$id}' ";
 $pan1=queryone($sql);
 if(!empty(getsession('username','shop'))){

    $uid=getsession('id','shop');
   
  
    $sql="SELECT id,price,uid,quantity,products FROM {$prefix}cart WHERE uid='{$uid}'";
    
    $pan2=queryone($sql);
    
    if(!empty($pan2)){
               $products= json_decode($pan2['products'],true);

               if(array_key_exists($id,$products)){
                    $products[$id]['quantity']=$quantity+$products[$id]['quantity'];
               }else{
                    $products[$id]=['quantity'=>$quantity,'products'=>$pan1];
               }
               $price=$quantity*$pan1['price']+$pan2['price'];
            $newquantity=$quantity+$pan2['quantity'];
               $products=addslashes(json_encode($products));

               $sql="UPDATE {$prefix}cart SET  price='$price' , products='$products',quantity='$newquantity'
                      WHERE uid='{$uid}'";
                var_dump($sql);
               execute($sql);   
           
    }else{
        $date=date('Y-m-d H:i:s');
        $products[$id]=['quantity'=>$quantity,'products'=>$pan1];
        $price=$pan1['price']* $quantity;
        $products=addslashes(json_encode($products)); 
          // json_encode(value); 把数组转坏为字符集 json_decode($pan2['products'],true);
        // addslashes(str)把特殊字符转化
        $sql="INSERT INTO {$prefix}cart(products,price,quantity,uid,created_at) 
            VALUES('$products','$price','$quantity','$uid','$date')";
        execute($sql);
    }
    header('location:cart.php');
 }else{

    $cart=getsession('cart4','shop');
    if(!empty($cart)){
          $products=$cart['products'];        
         if(array_key_exists($id,$products)){
                $products[$id]['quantity']=$quantity+$products[$id]['quantity'];     
         }else{
                $products[$id]=['quantity'=>$quantity,'product'=>$pan1];
               
         }
        $price=$pan1['price']*$quantity+$cart['price'];
         $newquantity=$quantity+$cart['quantity'];
         $cart_array=[
                'quantity'=>$newquantity,
                'price'=>$price,
                'products'=>$products
         ];
          setsession('cart4',$cart_array,'shop');
        var_dump(getsession('cart4','shop'));

    }else{
            $products[$id]=['quantity'=>$quantity,'product'=>$pan1];
            $price=$quantity*$pan1['price'];
            $cart_array=[
                'quantity'=>$quantity,
                'price'=>$price,
                'products'=>$products
            ];

            setsession('cart4',$cart_array,'shop');
            var_dump(getsession('cart4','shop'));

    }

 }
 